package com.scs.application.modules.dept.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.BeanUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.dept.entity.*;
import com.scs.application.modules.dept.mapper.UseMergeDtlMapper;
import com.scs.application.modules.dept.mapper.UseMergeMapper;
import com.scs.application.modules.dept.service.OprtUseItemService;
import com.scs.application.modules.dept.service.OprtUseService;
import com.scs.application.modules.dept.service.UseDtlService;
import com.scs.application.modules.dept.service.UseMergeDtlService;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class UseMergeDtlServiceImpl extends BaseServiceImpl<UseMergeDtlMapper, UseMergeDtl> implements UseMergeDtlService {
    @Autowired
    private UseDtlService useDtlService;
    @Autowired
    private UseMergeMapper useMergeMapper;
    @Autowired
    private OprtUseItemService oprtUseItemService;
    @Autowired
    private OprtUseService oprtUseService;

    @Override
    public boolean autoMerge(String useMergeId) {

        // 当天当前科室消耗单明细
        List<UseDtl> useDtlList = useDtlService.listCurrDateAndDept();

        // 过滤已合并消耗单 获取合单明细
        List<UseMergeDtl> mergeDtls = getUseMergeDtlList(useDtlList, useMergeId);

        // 保存合单明细
        return saveOrUpdateBatch(mergeDtls);
    }

    @Override
    public List<UseMergeDtl> getUseMergeDtlList(List<UseDtl> useDtlList, String useMergeId){
        if (useDtlList.isEmpty()){
            throw new BusinessException("没有可用的消耗单单据");
        }
        // 过滤 未合并的消耗单明细
        List<String> existUseDtlIds = this.list().stream().map(o -> o.getRefId()).collect(Collectors.toList());
        if (!existUseDtlIds.isEmpty()){
            useDtlList = useDtlList.stream().filter(o -> false == existUseDtlIds.contains(o.getId())).collect(Collectors.toList());
        }

        if (useDtlList.isEmpty()){
            throw new BusinessException("没有可用的消耗单单据");
        }

        List<UseMergeDtl> mergeDtls = Lists.newArrayList();
        UseMergeDtl useMergeDtl;
        for (UseDtl useDtl : useDtlList) {
            useMergeDtl = new UseMergeDtl();
            BeanUtils.copyProperties(useDtl, useMergeDtl);
            useMergeDtl.setId(null);
            useMergeDtl.setUseMergeId(useMergeId).setRefId(useDtl.getId()).setStockId(useDtl.getStockId())
                    .setMatrId(useDtl.getMatrId()).setMatrName(useDtl.getMatrName()).setMatrSpec(useDtl.getMatrSpec())
                    .setPackageQty(useDtl.getPackageQty()).setPackageUnit(useDtl.getPackageUnit())
                    .setSkuPrice(useDtl.getSkuPrice()).setSkuQty(useDtl.getSkuQty()).setAmount(useDtl.getAmount())
                    .setLot(useDtl.getLot()).setSnNo(useDtl.getSnNo()).setRfid(useDtl.getRfid()).setRemark("人工合单")
                    .setUser(UserUtils.currentUser().getName()).setUseTime(new Date());
            mergeDtls.add(useMergeDtl);
        }
         return mergeDtls;
    } @Override
    public boolean autoMergeOprtUse(String inpatientNo, String useMergeId, Boolean flagLine, String deptId) {

        // 获取病人消耗单明细
        List<OprtUseItem> oprtUseItemList = oprtUseItemService.listByOprtCodeAndDept(inpatientNo,flagLine,deptId);

        // 过滤已合并消耗单 获取合单明细
        List<UseMergeDtl> mergeDtls = getUseMergeDtlListByOprt(oprtUseItemList, useMergeId);

        // 保存合单明细
        return saveOrUpdateBatch(mergeDtls);
    }

    @Override
    public List<UseMergeDtl> getUseMergeDtlListByOprt(List<OprtUseItem> oprtUseItemList, String useMergeId){
        if (oprtUseItemList.isEmpty()){
            throw new BusinessException("没有可用的消耗单单据");
        }
        // 过滤 未合并的消耗单明细
        List<String> existUseDtlIds = this.list().stream().map(o -> o.getRefItemId()).collect(Collectors.toList());
        if (!existUseDtlIds.isEmpty()){
            oprtUseItemList = oprtUseItemList.stream().filter(o -> false == existUseDtlIds.contains(o.getId())).collect(Collectors.toList());
        }

        if (oprtUseItemList.isEmpty()){
            throw new BusinessException("没有可用的消耗单单据");
        }

        List<UseMergeDtl> mergeDtls = Lists.newArrayList();
        UseMergeDtl useMergeDtl;
        for (OprtUseItem oprtUseItem : oprtUseItemList) {
            OprtUse oprtUseDb = oprtUseService.getById(oprtUseItem.getDeptOprtUseId());
            useMergeDtl = new UseMergeDtl();
            BeanUtils.copyProperties(oprtUseItem, useMergeDtl);
            useMergeDtl.setId(null);
            useMergeDtl.setUseMergeId(useMergeId).setRefItemId(oprtUseItem.getId()).setRefId(oprtUseItem.getDeptOprtUseId())
                    .setRefTable("dept_oprt_use").setStockId(oprtUseItem.getStockId())
                    .setMatrId(oprtUseItem.getMatrId()).setMatrName(oprtUseItem.getMatrName()).setMatrSpec(oprtUseItem.getMatrSpec())
                    .setPackageQty(oprtUseItem.getPackageQty()).setPackageUnit(oprtUseItem.getPackageUnit())
                    .setSkuPrice(oprtUseItem.getSkuPrice()).setSkuQty(oprtUseItem.getSkuQty()).setAmount(oprtUseItem.getAmount())
                    .setLot(oprtUseItem.getLot()).setExpDate(oprtUseItem.getExpDate()).setSnNo(oprtUseItem.getSn())
                    .setRfid(oprtUseItem.getRfid()).setRemark("人工合单")
                    .setUser(oprtUseDb.getFlowModifier()).setUseTime(oprtUseDb.getBusDate());
            mergeDtls.add(useMergeDtl);
        }
        return mergeDtls;
    }


    @Override
    public boolean saveOrUpdateBatch(Collection<UseMergeDtl> entityList) {
        boolean b = super.saveOrUpdateBatch(entityList);

        // 修改合单金额
        String useMergeId = entityList.stream().findFirst().get().getUseMergeId();
        updateMergeAmount(useMergeId);

        return b;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        // 修改合单金额
        List<String> mergeIdList = this.listObjs(Wrappers.<UseMergeDtl>query()
                .select("use_merge_id")
                .in("id", idList)
                .groupBy("use_merge_id"), v -> v.toString());
        boolean b = super.removeByIds(idList);
        for (String mergeId : mergeIdList) {
            updateMergeAmount(mergeId);
        }

        return b;
    }

    private void updateMergeAmount(String useId) {
        Double total = calcMergeAmount(useId);

        // 修改订单总金额
        UseMerge useMerge = new UseMerge();
        useMerge.setAmount(total).setId(useId);
        useMergeMapper.updateById(useMerge);
    }

    private Double calcMergeAmount(String useMergeId) {
        Double totalAmount = this.getObj(Wrappers.<UseMergeDtl>query().select("sum(amount)" ).eq("use_merge_id" , useMergeId), v -> {
            if (v == null) {
                return 0.0;
            }
            return Double.valueOf(v.toString());
        });
        return totalAmount;
    }
}
